// pages/databaseGuide/databaseGuide.js

const app = getApp()
import * as echarts from '../../components/ec-canvas/echarts';

function setTodayOption(chart, weight) {
    const option = {
        series: [
            {
                name: '业务指标',
                type: 'gauge',
                data: [{value: weight, name: '今日体重'}]
            }
        ]
    };
    chart.setOption(option);
}

function setOption(chart, month) {
    console.log("setOption")
    let healthList = {}
    //获取当前健康信息
    wx.cloud.callFunction({
        name: 'getHealthList_rdl',
        data: {
            month: month
        },
    }).then((res) => {
        console.log('[云函数] [getHealthList_rdl] : ', res)
        res.result.weightList.forEach(it => {
            healthList[it.time] = it.weight
        })

        //获取一个月所有天数
        let monthList = getMonthList(new Date(month))
        console.log("月份列表", monthList)
        //横坐标
        let dataX = []
        //纵坐标
        let dataY = []
        let max = 60;
        let min = 60;


        console.log("healthList", healthList)
        for (let i = 0; i < monthList.length; i++) {
            dataX.push(i + 1)
            if (healthList[monthList[i]]) {
                dataY.push(healthList[monthList[i]])
                //计算坐标轴最大值
                if (healthList[monthList[i]] > max) {
                    //取十位
                    let max_ = parseInt((healthList[monthList[i]] % 100) / 10)+1;
                    max = max_ * 10
                    console.log("取十位",max_,max)
                }
                //计算坐标轴最小值
                if (healthList[monthList[i]] < max) {
                    //取十位
                    let min_ = parseInt((healthList[monthList[i]] % 100) / 10)-1;
                    if(min_<0){
                        min_=0
                    }
                    min = min_ * 10
                }
            } else {
                dataY.push(null)
            }
        }
        console.log("max min dataX  dataY",max,min, dataX, dataY)


        const option = {
            grid: {
                left: 10,
                right: 10,
                bottom: 10,
                top: 10,
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: dataX,
            },
            yAxis: {
                min: min,
                max: max,
                type: 'value'

            },
            series: [{
                data: dataY,
                type: 'line'
            }]
        };
        chart.setOption(option);


    })


}


Page({


    data: {
        date: "",
        show: false,
        showDataList: false,
        weightMax: "",
        weightMin: "",
        timeMax: "",
        timeMin: "",
        expDays: "",
        signDays: "",
        change: "",
        currentDateHealth: "",
        ec: {
            lazyLoad: true
        }
    },


    reLoadData() {
        //获取健康汇总信息
        wx.cloud.callFunction({
            name: 'getHealthData_rdl',
            data: {},
        }).then((res) => {
            console.log('[云函数] [getHealthData_rdl] : ', res)
            this.setData({
                weightMax: res.result.weightMax,
                weightMin: res.result.weightMin,
                timeMax: res.result.timeMax,
                timeMin: res.result.timeMin,
                expDays: res.result.expDays,
                signDays: res.result.signDays,
                change: res.result.change,
            })
            if(this.data.signDays>0){
                this.setData({
                    showDataList: true,
                })
            }
        });

        //获取当前健康信息
        wx.cloud.callFunction({
            name: 'getCurrentDateHealth_rdl',
            data: {},
        }).then((res) => {
            console.log('[云函数] [getCurrentDateHealth_rdl] : ', res)
            this.setData({
                currentDateHealth: res.result.currentDateHealth,
            })
            this.todayHealthChart(this.data.currentDateHealth==null?0:this.data.currentDateHealth.weight)
        })
        
        //刷新图表信息
        this.refreshChart()
    },


    onShow() {
        this.reLoadData()
    },
    openPop() {
        this.setData({
            show: true,
        })
    },
    closePop() {
        this.setData({
            show: false,
        })
    },
    afterAddWeight(e) {
        console.log('[云函数] [ e.detail options] : ', e.detail, e.options)
        this.closePop()
        this.reLoadData()
    },

    bindDateChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            date: e.detail.value
        })
    },

    //今日体重仪表盘
    todayHealthChart(weight){
        console.log("今天的体重")
        this.ecComponent = this.selectComponent('#today-health-chart');
        this.ecComponent.init((canvas, width, height, dpr) => {
            // 获取组件的 canvas、width、height 后的回调函数
            // 在这里初始化图表
            const chart = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr // new
            });
            //设置数据
            setTodayOption(chart, weight);
            // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
           
            return chart;
        });
    },

    //趋势图表相关
    refreshChart(e) {
        let month = getNowFormatMonth()
        if (e) {
            console.log('picker发送选择改变，携带值为', e.detail.value)
            this.setData({
                date: e.detail.value
            })
            month = e.detail.value
        } else {
            this.setData({
                date: month
            })
        }

        this.ecComponent = this.selectComponent('#health-chart');
        this.ecComponent.init((canvas, width, height, dpr) => {
            // 获取组件的 canvas、width、height 后的回调函数
            // 在这里初始化图表
            const chart = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr // new
            });
            //设置数据
            setOption(chart, month);
            // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
            this.chart = chart;
            // 注意这里一定要返回 chart 实例，否则会影响事件处理等
            return chart;
        });
    },


})

function getNowFormatMonth() {
    let date = new Date();
    let sep = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    let currentDate = year + sep + month
    return currentDate;
}

function getMonthList(times) {
    let Y = times.getFullYear();
    let M = times.getMonth() + 1;
    if (M >= 1 && M <= 9) {
        M = "0" + M;
    }
    let dateArr = [];
    if (M == 1 || M == 3 || M == 5 || M == 7 || M == 8 || M == 10 || M == 12) {
        for (let i = 1; i <= 31; i++) {
            let d = i
            if (d >= 1 && d <= 9) {
                d = "0" + d;
            }
            dateArr[i - 1] = Y + "-" + M + "-" + d;
        }
    } else if (M == 4 || M == 6 || M == 9 || M == 11) {
        for (let i = 1; i <= 30; i++) {
            let d = i
            if (d >= 1 && d <= 9) {
                d = "0" + d;
            }
            dateArr[i - 1] = Y + "-" + M + "-" + d;
        }
    } else {
        if (((Y % 4) == 0) && ((Y % 100) != 0) || ((Y % 400) == 0)) {   //闰年
            for (let i = 1; i <= 29; i++) {
                let d = i
                if (d >= 1 && d <= 9) {
                    d = "0" + d;
                }
                dateArr[i - 1] = Y + "-" + M + "-" + d;
            }
        } else {
            for (let i = 1; i <= 28; i++) {
                let d = i
                if (d >= 1 && d <= 9) {
                    d = "0" + d;
                }
                dateArr[i - 1] = Y + "-" + M + "-" + d;
            }
        }
    }
    return dateArr
}
